<template>
  <div>
    <Item
      v-for="data in shopCar"
      :key="data.id"
      v-bind="data"
      :increment="increment"
      :decrement="decrement"
    />
    <hr />
    <p>总共有{{ total }}件商品</p>
  </div>
</template>

<script>
import Item from "./components/Item";
import { nanoid } from "nanoid";
export default {
  name: "App",
  components: {
    Item,
  },
  data() {
    return {
      shopCar: [
        { id: nanoid(), goodName: "iphone14", goodDesc: "更大更强", num: 1 },
        {
          id: nanoid(),
          goodName: "小米电视",
          goodDesc: "具有30-100英寸的各种尺寸",
          num: 2,
        },
        {
          id: nanoid(),
          goodName: "大众汽车",
          goodDesc: "修不好的大众,开不坏的丰田",
          num: 4,
        },
      ],
    };
  },
  computed: {
    total() {
      return this.shopCar.reduce((p, c) => p + c.num, 0);
    },
  },
  methods: {
    increment(id) {
      // console.log("+++++");
      this.shopCar.forEach((item) => {
        if (item.id === id) {
          item.num++;
        }
      });
    },
    decrement(id) {
      // console.log("-----");
      this.shopCar.forEach((item) => {
        if (item.id === id) {
          item.num--;
        }
      });
    },
  },
};
</script>

<style></style>
